package cn.hinglo.common.interceptors.log;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.ContentType;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;
import com.jfinal.render.Render;
import com.jfinal.render.TextRender;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/***
 * @description: 全局的日志记录拦截器
 * @author HingLo
 * @date 2019-05-08
 */
@Slf4j
public class LogInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        HttpServletRequest request = controller.getRequest();
        // 具体日志信息记录实现
        long startTime = System.currentTimeMillis();
        //全路径
        String url = request.getRequestURL().toString();
        //请求的方法类型
        String method = request.getMethod();
        //请求的参数值
        String queryString = request.getQueryString();
        // 方法名称
        String name = inv.getMethod().getName();
        // 具体的类名称
        String classMethod = controller.getClass().getName() + "." + name;
        // 默认请求方式就打印参数,其他的就默认打印请求内容
        String contentType = request.getHeader("Content-Type");
        if (StrUtil.isBlank(contentType) || ContentType.FORM_URLENCODED.toString().equals(contentType)) {
            log.info("请求开始 URL: {} ==> method: {} ==> classMethod:{} ==> params: {}", url, method, classMethod, URLUtil.decode(queryString));
        } else if (StrUtil.isNotBlank(contentType) && contentType.contains(ContentType.MULTIPART.toString())) {
            log.info("文件请求开始 URL: {} ==> method: {} ==> classMethod:{} ==>params: {}", url, method, classMethod, URLUtil.decode(queryString));
        } else {
            log.info("请求开始 URL: {} ==> method: {} ==> classMethod:{} ==>params: {}, body: {}", url, method, classMethod, URLUtil.decode(queryString), controller.getRawData());
        }
        inv.invoke();
        long millis = System.currentTimeMillis() - startTime;
        log.info("请求结束 URL: {} ==>millis: {}==> response: {}", url, millis, getReturning(controller.getRender()));
    }


    private String getReturning(Render render) {
        if (render == null) {
            return "未达到controller方法中就发生异常,未拦截到响应数据";
        }
        if (render instanceof JsonRender) {
            return ((JsonRender) render).getJsonText();
        } else if (render instanceof TextRender) {
            return ((TextRender) render).getText();
        }
        return render.getClass().getSimpleName() + "=>" + render.getView();
    }

}
